package com.yx.front.security;

import com.alibaba.fastjson.JSON;
import com.yx.front.config.global.BizException;
import com.yx.front.config.global.CommonResult;
import com.yx.front.model.SysUser;
import com.yx.front.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author YangXiong
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public CommonResult<HashMap<String, String>> login(SysUser sysUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUserName(), sysUser.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authentication)) {
            throw new BizException("登录失败");
        }
        LoginUser user = (LoginUser) authentication.getPrincipal();
        SysUser returnUser = user.getSysUser();
        String token = JwtUtil.createJwt(returnUser.getId().toString());
        HashMap<String, String> map = new HashMap<>(4);
        map.put("token", token);
        map.put("userName", returnUser.getUserName());
        map.put("headUrl", returnUser.getAccount());
        map.put("role", "role");
        //写入缓存
        Long userId = returnUser.getId();

        redisTemplate.opsForValue().set("login:" + userId, JSON.toJSONString(user));
        return CommonResult.success(map);
    }

    @Override
    public CommonResult<String> logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getSysUser().getId();
        redisTemplate.delete("login:" + userId);
        return CommonResult.success("退出成功");
    }
}
